package cn.yanhu.kuwanapp.user

import android.content.Context
import android.content.Intent
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import cn.woochen.comlib.BaseActivity
import cn.woochen.comlib.util.*
import cn.woochen.comlib.util.ext.setOnSingleClickListener
import cn.yanhu.kuwanapp.AppApplication
import cn.yanhu.kuwanapp.R
import cn.yanhu.kuwanapp.common.activity.CommonWebviewActivity
import cn.yanhu.kuwanapp.databinding.ActivityLoginBinding
import cn.yanhu.kuwanapp.event.AccountLoginEvent
import cn.yanhu.kuwanapp.home.MainActivity
import cn.yanhu.kuwanapp.utils.Config
import cn.yanhu.kuwanapp.utils.DeviceInfoUtil
import cn.yanhu.kuwanapp.utils.SimpleDialogUtil
import cn.yanhu.kuwanapp.utils.constans.Constants
import cn.yanhu.kuwanapp.utils.ext.parseState
import cn.yanhu.kuwanapp.utils.ext.showToast
import cn.yanhu.kuwanapp.utils.third.AccountType
import cn.yanhu.kuwanapp.utils.third.ThirdAccountHelper
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tbruyelle.rxpermissions3.RxPermissions
import me.jessyan.autosize.internal.CustomAdapt
import java.util.jar.Manifest

/**
 * 类描述：登录
 * @author：woochen
 * create at：2021/7/25 1:17 PM
 */
class LoginActivity : BaseActivity<ActivityLoginBinding, UserViewModel>(), OnSingleClickListener ,
    CustomAdapt {
    private var exitTime: Long = 0
    private var mUserId by UserPref(Constants.USER_ID, "")
    private var mToken by UserPref(Constants.USER_TOKEN, "")

    override fun setContentView(): Int = R.layout.activity_login

    override fun initData() {
        setStatusBarStyle(false)
        initWidgets()
    }

    private var isAgreePrivacy by ConfigPref(Constants.IS_AGREE_PRIVACY, false)


    private fun initWidgets() {
        if (!isAgreePrivacy){
            SimpleDialogUtil.privacyDialog(mContext,{
                ActivityUtil.appExit(mContext)
            },{
                (application as AppApplication).initSdk()
            })
        }
        //审核模式开始手机号登录
//        mBinding.tvPhoneLogin.isVisible = Constants.isExamine
    }

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        //微信登录授权成功
        LiveEventBus.get(AccountLoginEvent::class.java).observe(this, Observer {
            val wxCode = it.code ?: ""
            mViewModel.wxlogin(wxCode,"1")
        })
        //微信登录成功
        mViewModel.wxloginInfo.observe(this, Observer { it ->
            parseState(it,{
                mUserId = it.login.userId
                mToken = it.login.token
                if (it.isBindPhone){
                    showToast("登录成功!")
                    ActivityUtil.finishAllActivity()
                    MainActivity.start(this)
                    back()
                }else{
                    PhoneLoginActivity.start(this,"手机号绑定",it.weChatData)
                    back()
                }
            })
        })
    }

    override fun onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            showToast(R.string.tip_exit)
            exitTime = System.currentTimeMillis()
        } else {
            ActivityUtil.appExit(mContext)
        }
    }

    private val mRxPermissions by lazy {
        RxPermissions(this)
    }

    private var mImei by UserPref(Constants.IMEI, "")

    override fun initListener() {
        mBinding.llWxLogin.setOnSingleClickListener(this)
        mBinding.tvPhoneLogin.setOnSingleClickListener(this)
        mBinding.tvRegisterProtocol.setOnSingleClickListener(this)
        mBinding.tvPrivacyProtocol.setOnSingleClickListener(this)
    }

    override fun onSingleClick(v: View?) {
        when (v) {
            mBinding.llWxLogin -> { //微信一键登录
                if (!mBinding.cbAgree.isChecked){
                    showToast("请先阅读并同意协议!")
                    return
                }
                mRxPermissions.request(android.Manifest.permission.READ_PHONE_STATE).subscribe {
                    if (it){
                        mImei = DeviceInfoUtil.getIMEI(ApplicationUtil.context)
                        ThirdAccountHelper.sendAuthReq(AccountType.WX)
                    }else{
                        showToast("权限不足，请在设置中打开!")
                    }

                }
            }
            mBinding.tvPhoneLogin -> { //手机号登录
                if (!mBinding.cbAgree.isChecked){
                    showToast("请先阅读并同意协议!")
                    return
                }
                mRxPermissions.request(android.Manifest.permission.READ_PHONE_STATE).subscribe {
                    if (it){
                        mImei = DeviceInfoUtil.getIMEI(ApplicationUtil.context)
                        PhoneLoginActivity.start(mContext)
                    }else{
                        showToast("权限不足，请在设置中打开!")
                    }
                }
            }
            mBinding.tvRegisterProtocol -> { //注册协议
                CommonWebviewActivity.start(mContext, Config.USER_AGREEMENT,true)
            }
            mBinding.tvPrivacyProtocol -> { //隐私协议
                CommonWebviewActivity.start(mContext, Config.USER_PRIVATE_AGREEMENT,true)
            }

        }
    }

    companion object {

        fun start(context: Context) {
            val intent = Intent(context, LoginActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun isBaseOnWidth(): Boolean = false

    override fun getSizeInDp(): Float = 720f
}